/*
 * @Descripttion:
 * @version:
 * @Author: sueRimn
 * @Date: 2019-10-22 14:39:05
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-09-02 17:45:02
 */
import axios from 'axios'
import store from '@/store'
import router from '../router'
import { Message } from 'element-ui'
axios.defaults.timeout = 30000
axios.defaults.withCredentials = true // 跨域请求，允许保存cookie
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
	if (store.getters.token && sessionStorage.getItem('token')) {
		config.headers['Authorization'] = store.getters.token // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
	}
	return config
}, function (error) {
	console.log('error' + error)
	return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
	if (response.data.code == 401) {
    store.commit('user/SET_TOKEN', '')
    store.commit('user/SET_ROLE', '')
    store.commit('user/SET_PERMISSION', [])
    store.commit('user/SET_USER_INFO', {})
    store.commit('common/CLEAR_TAG')
    router.push('/login')
    // Message.error('登录状态已过期，请重新登录')
    Message.error(response.data.msg)
    return Promise.reject(new Error(response.data.msg))
  }
  if (response.data.code == 405) {
    store.commit('user/SET_TOKEN', '')
    store.commit('user/SET_ROLE', '')
    store.commit('user/SET_PERMISSION', [])
    store.commit('user/SET_USER_INFO', {})
    store.commit('common/CLEAR_TAG')
    router.push('/login')
    Message.error(response.data.msg)
  }
  if (response.data.code == 500) {
    Message.error('系统开小差了,请稍后重试')
  }
	return response
}, function (error) {
  console.log(error)
  let msg = ''
  if (error.message == 'timeout of 30000ms exceeded') {
    Message.error('请求超时，请稍后重试')
    msg = '请求超时，请稍后重试'
  }
  if (error.message == 'Network Error') {
    Message.error('网络异常，请稍后重试')
    msg = '网络异常，请稍后重试'
  }
	return Promise.reject(new Error(msg))
})
export default axios
